package com.niiwoo.civet.trade.service.local.contract;

import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.trade.service.local.contract.vo.BorrowerContractDTO;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 信息查询授权书
 *
 * @author liaojunjun
 */
@Service
public class InformationInquiryAuthorization extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(InformationInquiryAuthorization.class);

    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ContractBaseService contractBaseService;

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        logger.info("信息查询授权书处理开始... projectId:{}", project.getProjectId());

        // 构建信息查询授权书所需数据
        BorrowerContractDTO contractDTO = contractBaseService.getBorrowerContractDTO(project.getProjectId());
        contractDTO.setContractId(snowflakeIdWorker.nextId() + ""); //合同ID

        this.generateContract(contractTemplate, contractDTO, project);

        ProjectContract result = this.signContract(contractTemplate, contractDTO, project);

        this.contractFilling(contractDTO.getContractId());

        logger.info("信息查询授权书处理结束... projectId:{}", project.getProjectId());

        return result;
    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, BorrowerContractDTO contractDTO, Project project) throws Exception {
        logger.info("信息查询授权书生成开始... projectId:{}", project.getProjectId());

        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();
        dto.setContractId(contractDTO.getContractId());
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());

        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("authorizer", contractDTO.getBorrowerUserName());
        parameterMap.put("idCard", privacyMasks.maskIdCardSixTwo(contractDTO.getBorrowerIdCard()));
        parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));
        dto.setParameterMap(parameterMap);
        generateContract(dto);

        logger.info("信息查询授权书生成结束... projectId:{}", project.getProjectId());
    }

    private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, BorrowerContractDTO contractDTO, Project project) throws Exception {
        logger.info("法大大合同自动签署-信息查询授权书 projectId:{}", project.getProjectId());

        // 借款人签署
        String transactionId = snowflakeIdWorker.nextId() + "";
        String docTitle = contractDTO.getBorrowerUserName() + "的信息查询授权书_" + contractDTO.getContractId();
        String borrowerSignKeyword = contractDTO.getBorrowerUserName();

        FadadaResponseDTO fadadaResponse = extSignAuto(transactionId, contractDTO.getContractId(), contractDTO.getFadadaCacertId(),
                SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
        logger.info("法大大合同自动签署-信息查询授权书 借款人签署结束... projectId:{}", project.getProjectId());

        return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), contractDTO.getContractId(), transactionId,
                fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }

}
